package com.kenans.interceptor;

import com.kenans.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author KENANS
 * @date 2020-8-26 12:14
 * @Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User loginUser = (User)request.getSession().getAttribute("loginUser");

         // 判断是否登录，未登录loginUser是空的，要拦截的；
        if (loginUser == null) {
            // 使用Ajax请求时，会有特殊的请求头，区别是Ajax请求还是 controller .do 请求
            String header = request.getHeader("X-Requested-With");
            if (header != null && header.equals("XMLHttpRequest")) {
                // ajax 请求时，他需要的是一个json数据
                response.getWriter().write("'code':0, 'info':'未登录'");
            } else {
                response.sendRedirect(request.getContextPath() + "/pagehome/login.html");
            }
            return false;
        } else {
            return true;
        }
    }
}
